package com.stef.saas.crm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stef.saas.common.base.constant.CommonConstants;
import com.stef.saas.common.base.dto.BaseResult;
import com.stef.saas.common.base.enums.ErrorCodeEnum;
import com.stef.saas.common.base.exception.BusinessException;
import com.stef.saas.crm.mapper.CustomerMapper;
import com.stef.saas.crm.model.dto.CustomerDTO;
import com.stef.saas.crm.model.dto.CustomerPageDTO;
import com.stef.saas.crm.model.entity.Customer;
import com.stef.saas.crm.model.vo.CustomerVO;
import com.stef.saas.crm.service.ICustomerService;
import com.stef.saas.ssm.feign.UmsClient;
import com.stef.saas.ssm.feign.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author stef
 * @date 2021-05-15
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Override
    public BaseResult pageListCustomer(Page page,CustomerPageDTO pageDTO){
        Customer customer = new Customer();
        BeanUtils.copyProperties(pageDTO, customer);
        return BaseResult.ok(this.page(page, Wrappers.query(customer)));
    }

    @Override
    public BaseResult doSave(CustomerDTO dto){
        Customer customer = new Customer();
        BeanUtils.copyProperties(dto, customer);
        return BaseResult.ok(this.save(customer));
    }

    @Override
    public BaseResult doDelete(Integer id){
        return BaseResult.ok(this.removeById(id));
    }


    @Override
    public BaseResult doUpdate(CustomerDTO dto){
        Customer customer = new Customer();
        BeanUtils.copyProperties(dto, customer);
        return BaseResult.ok(this.updateById(customer));
    }

    @Autowired
    UmsClient umsClient;

    @Override
    public BaseResult detail(Integer id){
        CustomerVO vo = new CustomerVO();
        Customer customer = this.getById(id);
        if (null == customer){
            throw new BusinessException(ErrorCodeEnum.CRM20001);
        }
        BeanUtils.copyProperties(customer, vo);
        if (customer.getUserId() != null){
            BaseResult<User> umsClientUser = umsClient.getById(Long.valueOf(customer.getUserId()));
            if (umsClientUser.getCode()== CommonConstants.SUCCESS){
                vo.setUser(umsClientUser.getData());
            }
        }
        return BaseResult.ok(vo);
    }
}
